package main

import (
	"context"
	"log"
	"sync"
	"time"
)

func main() {
	var wg sync.WaitGroup
	wg.Add(1)

	ctx, stop := context.WithCancel(context.Background())

	go func() {
		defer wg.Done()
		watchData(ctx, "监控1")
	}()

	time.Sleep(time.Second * 3) //先监控3秒钟
	stop()                      //发送停止的信号
	wg.Wait()
}

func watchData(ctx context.Context, name string) {
	//死循环中一直监控后台数据
	for {
		select {
		case <-ctx.Done():
			log.Println(name, "已收到停止监控的指令,不再监控")
			return
		default:
			log.Println(name, "正在监控中...")
		}
		time.Sleep(time.Second)
	}
}
